<?php
/*
 * @description: Модель для работы с предметами
 * @copyright Copyright (c) 2012-2017 Marin V. , Tykva A. , Kozel R. , Sokolov D.
 * @version 1.0
 * @link http://lecturebox.ru
*/

class Model_Subject
{
    protected $lecture_id;

    protected $_dbTable;
    protected $_row;
    
    protected $data;

    public function __construct($lecture_id=0)
    {
        $this->lecture_id = $lecture_id;
        $this->data = null;

        $this->_dbTable = new Model_DbTable_Subjects();
        if($lecture_id)
            $this->_row = $this->_dbTable->find($lecture_id)->current();
        else
            $this->_row = $this->_dbTable->createRow();
    }

    public function getAllSubjects()
    {
        return $this->_dbTable->fetchAll();
    }   

    public function getSubjectById($id)
    {   
        $select = $this->_dbTable->select();
        $select->where('subject_id = ?', $id);
        return $this->_row = $this->_dbTable->fetchAll($select);
    }    
    
    /**
     * Возвращает объект Zend_Paginator для вывода записей постранично
     * @param int $page
     * @param int $perPege
     * @return Zend_Paginator
     */
    public function getPaginatorRows($page = 1, $perPege = 10, $tag = 0, $cat = 0)
    {
        $adapter = new Model_Paginator_PageSubjects(Zend_Db_Table::getDefaultAdapter()->select());
     
        $adapter->tag = $tag;
        $adapter->cat = $cat;

        // Создаем Zend_Paginator - передаем в него полученый адаптер
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage($perPege);

        return $paginator;
    }    
    
    public function getSubjectsById($id)
    {   
        $select = $this->_dbTable->select();
        $select->where('subject_id = ?', $id);
        return $this->_row = $this->_dbTable->fetchAll($select);
    }
    
    public function __set($name, $val)
    {
        if (isset($this->_row->$name)) {
            $this->_row->$name = $val;
        }
    }

    public function __get($name)
    {
        if (isset($this->_row->$name)) {
            return $this->_row->$name;
        }
    }
    
    public function fill($data)
    {
        foreach ($data as $key => $value)
            if (isset($this->_row->$key))
                $this->_row->$key = $value;
    }

    public function save()
    {
        $this->_row->save();
    } 
    
    public function delSubject($subject_id)
    {   
        $where = array(
            'subject_id = ?' => $subject_id
        );        
        $this->_dbTable->delete($where); 
    }    
}
